package autoTest.request;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import autoTest.Holder;
import autoTest.command.ErrorCode;
import autoTest.command.Params;
import autoTest.database.DataElement;
import autoTest.database.DataManager;
import autoTest.device.DeviceInfo;
import autoTest.device.Platform;
import autoTest.utils.FileInfoReader;
import autoTest.utils.TextUtils;
import main.ServerMain;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class StartPart extends RequestPart {
	private static final long serialVersionUID = 2271797150647771298L;
	public StartPart() {}
    
	protected void doResponse(HttpServletResponse resp, int code, String taskId) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");  
		resp.setContentType("text/plain");
		resp.setStatus(HttpServletResponse.SC_OK);
		PrintWriter pWriter = resp.getWriter();
		JSONObject joRet = new JSONObject();
		joRet.put(Params.CODE, code);
		joRet.put(Params.TASK_ID, taskId);
		pWriter.println(joRet.toString());  
	}

	@Override public void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String deviceIdsStr = req.getParameter(Params.DEVICE_ID_LIST);
    	String pathListStr = req.getParameter(Params.TEST_PATH_LIST);
    	
    	if (deviceIdsStr == null || deviceIdsStr.equals("null")) {
    		deviceIdsStr = null;
    	}
    	if (pathListStr == null || pathListStr.equals("null")) {
    		pathListStr = null;
    	}
    	System.out.println("[StartPart] deviceIdsStr:" + deviceIdsStr);
    	System.out.println("[StartPart] pathListStr:" + pathListStr);
    	
    	List<String> allDevices = new ArrayList<String>();
    	List<String> allPaths = new ArrayList<String>();
    	if (TextUtils.isEmpty(pathListStr)) {		//不存在测试路径
    		System.out.println("[StartPart] " + ServerMain.getContext().getServletContext().getRealPath(""));
    		allPaths.add("");
    	} else {		//存在测试路径
    		System.out.println("[StartPart] provide file:" + pathListStr);
    		String[] tmp = pathListStr.split(",");
    		for (String ele : tmp) {
    			if (!TextUtils.isEmpty(ele)) {
    				allPaths.add(ele);
    			}
    		}
    		
    		for (String ele : allPaths) {
    			File file = new File(ServerMain.getContext().getServletContext().getRealPath(ele));
    			if (FileInfoReader.getFolderSize(file) <= 0) {		//测试路径下没有可测试用例
    				doResponse(resp, ErrorCode.ERR_NO_TESTCASE, null);
    				return;
    			}
    		}
    	}
    	
    	System.out.println("[StartPart] step");
    	if (TextUtils.isEmpty(deviceIdsStr)) {		//不存在设备信息
    		System.out.println("[StartPart] provide no device");
    		for (String eleDeviceId : ServerMain.allDeviceInfo.keySet()) {
    			allDevices.add(eleDeviceId);			//所有当前正在连接的设备设置为执行设备
    		}
    	} else {
    		System.out.println("[StartPart] provide device:" + deviceIdsStr);
    		String[] tmp = deviceIdsStr.split(",");		//存在设备信息
    		for (String ele : tmp) {		//过滤设备信息为空的元素
    			System.out.println(ele);
    			if (!TextUtils.isEmpty(ele)) {
    				if (!ServerMain.allDeviceInfo.containsKey(ele)) {		//提供设备此时并没有连接上
    					doResponse(resp, ErrorCode.ERR_NO_DEVICE, null);
    					return;
    				} 
//    				
//    				else if (ServerMain.allDeviceInfo.get(ele).getStatus() == Status.BUSY) {		//存在连接的设备正在运行测试用例
//    					doPost(req, resp, ErrorCode.ERR_CASE_RUNNING, null);
//    					return;
//    				}
    				allDevices.add(ele);
    			}
    		}
    	}
    	
    	String taskId = "task-" + System.currentTimeMillis();
    	doResponse(resp, ErrorCode.SUCCESS, taskId);
    	
    	System.out.println("[StartPart] reponse curl");
    	
    	
    	DataElement element = new DataElement();
    	element.setTaskId(taskId);
    	String deviceIDS = new String("");
    	for (String ele : allDevices) {
    		Holder holder = ServerMain.allReponseMap.get(ServerMain.allDeviceReqMap.get(ele));
    		deviceIDS = deviceIDS + ele + ",";			
    		
    		JSONArray ja = new JSONArray();
    		System.out.println("[StartPart] " + ele + " <> " + taskId);
    		DeviceInfo di = ServerMain.allDeviceInfo.get(ele);
    		Platform pf = null;
    		if (di != null) {
    			pf = di.getPlatform();
    		}
    		for (String path : allPaths) {
    			File file = new File(ServerMain.getContext().getServletContext().getRealPath(path));
    			FileInfoReader.readServerFiles(file, ja, pf);
    		}
    		holder.getListener().makeIt(0, ja.toString(), taskId, null);
    		holder.getContinuation().complete();
    	}
    	element.setDeviceSet(deviceIDS.substring(0, deviceIDS.length() - 1));
    	DataManager.putResult(element);	//对指定的请求添加执行设备的信息
	}
}
